#!/bin/sh
# 
# Genera un listado con todos los procesos hijos del proceso llamado.

usage(){
	echo "Informacion de los procesos hijos"
	echo "Uso: $0 -c / -p | <nombre proceso> / <pid>"
}

n_args=2

if [ $# -ne "$n_args" ];
then
	usage
	exit 0
fi

# FIX: Implements version with 1 call only to `ps`
#a=`ps -eo pid,fname,ppid | grep -v PID`
#all_proc=($a)
#echo "${all_proc[4]}"

main_pid=""
main_fname=""
main_ppid=
father_pid=""
father_fname=""

fname=`ps -eo fname | grep -v COMMAND`
pid=`ps -eo pid | grep -v PID`
ppid=`ps -eo ppid | grep -v PPID`

all_proc_fname=($fname)
all_proc_pid=($pid)
all_proc_ppid=($ppid)

n_all_proc_fname=${#all_proc_fname[*]}
n_all_proc_pid=${#all_proc_pid[*]}
n_all_proc_ppid=${#all_proc_ppid[*]}


if [[ "$1" == "-c" ]]; 
then
	main_fname="$2"
	for ((i=0; $i<$n_all_proc_fname; i++));
	do
		if [[ "${all_proc_fname[$i]}" == "$main_fname" ]];
		then
			main_pid=${all_proc_pid[$i]}
			main_ppid=${all_proc_ppid[$i]}
			father_pid="$main_ppid"
		fi
	done
	if [[ -z "$main_pid" ]] || [[ -z "$main_ppid" ]]; 
	then
		echo "Proceso no encontrado en el sistema"
		exit 0
	fi
elif [[ "$1" == "-p" ]]; 
then
	main_pid="$2"
	for ((i=0; $i<$n_all_proc_pid; i++));
	do
		if [[ "${all_proc_pid[$i]}" -eq "$main_pid" ]];
		then
			main_fname=${all_proc_fname[$i]}
			main_ppid=${all_proc_ppid[$i]}
			father_pid="$main_ppid"
		fi
	done
	if [[ -z "$main_fname" ]] || [[ -z "$main_ppid" ]]; 
	then
		echo "Proceso no encontrado en el sistema"
		exit 0
	fi
fi

# Gets father_fname
for ((i=0; $i<$n_all_proc_pid;i++));
do
	if [[ "${all_proc_pid[$i]}" -eq "$father_pid" ]];
	then 	
		father_fname="${all_proc_fname[$i]}"
	fi
done

echo "########################"
echo "------$father_pid-------"
echo "------$father_fname-----"
echo "                       |"
echo "                       |"
echo "                       ##########################"
echo "                       -------$main_pid----------"
echo "                       -------$main_fname--------"
echo "                                                 |"
echo "                                                 |"
echo "                                                  #########################"
for ((i=0; $i<$n_all_proc_pid; i++));
do
	if [[ "${all_proc_ppid[$i]}" -eq "$main_pid" ]];
	then
		
	echo "                                                   ${all_proc_pid[$i]} - ${all_proc_fname[$i]}"
	fi
done

echo "Process PID: $main_pid"
echo "Process NAME: $main_fname"
echo "Process PPID: $main_ppid"
echo "Process FATHER PID: $father_pid"
echo "Process FATHER PPID: $father_fname"

exit 0
